package com.example.demo.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: xiatian
 * @CreateTime: 2022/2/26 3:33 下午
 * @Description: 生产者消费者
 */
public class ProducerConsum_oldversion {
    public static class ShareData {
        private int number = 0;
        private Lock lock = new ReentrantLock();
        private Condition condition = lock.newCondition();

        public void increment() throws InterruptedException {
            lock.lock();
            try {
                //资源不为空的时候
                while (number != 0) {
                    //等待，不能生成
                    condition.await();
                }
                //生产
                number++;
                System.out.println(Thread.currentThread().getName() + " " + number);
                condition.signalAll();
            } finally {
                lock.unlock();
            }
        }

        public void decrement() throws InterruptedException {
            lock.lock();
            try {
                //资源为空的时候
                while (number == 0) {
                    //等待不能消费
                    condition.await();
                }
                //消费
                number--;
                System.out.println(Thread.currentThread().getName() + " " + number);
                condition.signalAll();
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        ShareData s = new ShareData();

        new Thread(() -> {
            for (int i = 1; i <= 5; i++) {
                try {
                    s.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "AA").start();
        new Thread(() -> {
            for (int i = 1; i <= 5; i++) {
                try {
                    s.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "BB").start();
    }

}
